<?php

namespace app\task\cron\movie;

use yunwuxin\cron\Task;
use think\facade\Db;

/**
 * 守兔影票下单
 */
class Taototo extends Task
{
    /**
     * 每分钟执行1次
     */
    protected function configure()
    {
        // 分 时 日 月 周
        $this->expression = '* * * * *';
    }

    /**
     * 执行指令
     */
    protected function handle()
    {
        $lockKey = 'taototo_order_lock_key';
        $lockVal = cache($lockKey);
        if ($lockVal) {
            echo '还在处理呢' . PHP_EOL;
            return true;
        }

        cache($lockKey, 1, 120);

        $list = Db::name('taototo_order')
            ->where('status', 2)
            ->limit(30)
            ->select()
            ->toArray();
        $taototo = new \app\common\service\Taototo;
        $success = 0;
        $fail = 0;
        foreach ($list as $v) {
            $params = json_decode($v['params'], true);
            $res = $taototo->orderCreate($params);
            $res = json_decode($res, true);
            if (empty($res['code']) || $res['code'] != 200) {
                $v['message'] = $res['message'] ?? '下单失败';
                $this->handleFail($v, $res);
                $fail += 1;
            } else {
                $this->handleSuccess($res);
                $success += 1;
            }
        }

        cache($lockKey, null);

        echo '守兔下单完毕：成功 ' . $success . ' 单，失败 ' . $fail . ' 单' . PHP_EOL;
    }

    /**
     * 下单失败处理
     */
    private function handleFail($order, $res)
    {
        Db::name('taototo_order')
            ->where('order_id', $order['order_id'])
            ->update([
                'status' => 4,
                'result' => json_encode($res, JSON_UNESCAPED_UNICODE),
            ]);
        Db::name('movie_order')
            ->where('order_id', $order['order_id'])
            ->update([
                'supplier_status' => 10,
                'close_time' => time(),
                'close_cause' => $order['message'],
                'refund_status' => 2,
            ]);

        $notifyData = [
            'status' => 10,
            'close_cause' => $order['message'],
        ];
        if (!empty($order['notify_url'])) {
            $agent = Db::name('agent')
                ->field('app_key, app_secret')
                ->where('id', $order['agent_id'])
                ->find();
            $notifyData = array_merge($notifyData, [
                'order_id' => strval($order['order_id']),
                'out_order_id' => $order['out_order_id'],
                'app_key' => $agent['app_key'],
                'app_secret' => $agent['app_secret'],
            ]);
            Db::name('movie_notify_agent')
                ->insert([
                    'order_id' => $order['order_id'],
                    'notify_url' => $order['notify_url'],
                    'params' => json_encode($notifyData),
                    'status' => 1,
                    'send_time' => time(),
                    'result' => '',
                ]);
        }
    }

    /**
     * 下单成功处理
     */
    private function handleSuccess($res)
    {
        Db::name('taototo_order')
            ->where('order_id', $res['data']['third_order_id'])
            ->update([
                'status' => 3,
                'result' => json_encode($res, JSON_UNESCAPED_UNICODE),
            ]);
        Db::name('movie_order')
            ->where('order_id', $res['data']['third_order_id'])
            ->update([
                'supplier_status' => 2,
                'supplier_order_id' => $res['data']['order_id'],
            ]);
    }
}
